package cn.jee.redis;

import cn.jee.redis.domain.Stu;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class StuMis {
    private Jedis jedis;   
    public StuMis(){
        jedis=new Jedis();
    }
    //清空数据库
    public void clear(){
      jedis.flushAll();
    }
    //产生一个学生学号
    public long newId(){
      return jedis.incr("stu:id");
    }
    /**
     给Stu一个学号，然后保存在stu:学号的具体值的hash表中
     同时保存java成绩在sorted set中
     保存math成绩在sorted set中
     */
    public void add(Stu stu){
      if (stu.getId() == 0) {
        stu.setId(newId());
      }
      String key = "stu:" + stu.getId();
      jedis.hset(key, "id", String.valueOf(stu.getId()));
      jedis.hset(key, "username", stu.getUsername());
      jedis.hset(key, "math", String.valueOf(stu.getMath()));
      jedis.hset(key, "java", String.valueOf(stu.getJava()));
      jedis.zadd("stu:math", stu.getMath(), String.valueOf(stu.getId()));
      jedis.zadd("stu:java", stu.getJava(), String.valueOf(stu.getId()));
    }
    /**数学成绩最高的5个人的姓名*/
    public String[] top5ByMath(){
      List<String> ids = jedis.zrevrange("stu:math", 0, 4);
      List<String> names = new ArrayList<>();
      for (String id : ids) {
        names.add(jedis.hget("stu:" + id, "username"));
      }
      return names.toArray(new String[0]);
    }
    /**成绩在min和max之间的java成绩*/
    public double[] betweenJava(double min,double max){
      List<Tuple> set = jedis.zrangeByScoreWithScores("stu:java", min, max);
      return set.stream().mapToDouble(Tuple::getScore).toArray();
    }
    /**按学号查找，没有返回null*/
    public Stu findById(long id){
      String key = "stu:" + id;
      if (!jedis.exists(key)) return null;
      Stu stu = new Stu();
      stu.setId(id);
      stu.setUsername(jedis.hget(key, "username"));
      stu.setMath(Double.parseDouble(jedis.hget(key, "math")));
      stu.setJava(Double.parseDouble(jedis.hget(key, "java")));
      return stu;
    }
    /**按java成绩从低到高分页查询*/
    public List<Stu> pageByJava(int page,int size){
      int start = (page - 1) * size;
      int end = start + size - 1;
      List<String> ids = jedis.zrange("stu:java", start, end);
      List<Stu> list = new ArrayList<>();
      for (String id : ids) {
        Stu stu = findById(Long.parseLong(id));
        if (stu != null) list.add(stu);
      }
      return list;
    }
}